import os
import re
import shutil
from pathlib import Path

def convert_adoc_to_typst(adoc_content):
    """
    将AsciiDoc内容转换为Typst格式
    实现基本语法转换规则：
    - 标题
    - 列表
    - 代码块
    - 图片
    - 链接
    """
    # 标题转换 (1-5级)
    adoc_content = re.sub(r'^= (.+)$', r'#heading(level: 1)[\1]', adoc_content, flags=re.MULTILINE)
    adoc_content = re.sub(r'^== (.+)$', r'#heading(level: 2)[\1]', adoc_content, flags=re.MULTILINE)
    adoc_content = re.sub(r'^=== (.+)$', r'#heading(level: 3)[\1]', adoc_content, flags=re.MULTILINE)
    adoc_content = re.sub(r'^==== (.+)$', r'#heading(level: 4)[\1]', adoc_content, flags=re.MULTILINE)
    adoc_content = re.sub(r'^===== (.+)$', r'#heading(level: 5)[\1]', adoc_content, flags=re.MULTILINE)
    
    # 无序列表
    adoc_content = re.sub(r'^(\s*)\* ', r'\1- ', adoc_content, flags=re.MULTILINE)
    
    # 代码块处理（统一使用clojure格式）
    # 格式：[source]---- → ```clojure\n
    adoc_content = re.sub(r'\[source[^\]]*?\]\n----', r'```clojure\n', adoc_content)
    adoc_content = re.sub(r'----', r'```', adoc_content)
    
   
    # 图片
    adoc_content = re.sub(r'image::([^\[]+)\[\]', r'#image("\1")', adoc_content)
    
    # include 导入
    adoc_content = re.sub(r'include::(.+?)\.adoc\[\]', r'#include "\1.typ"', adoc_content)
    
    # 链接
    adoc_content = re.sub(r'link:([^\[]+)\[([^\]]+)\]', r'#link("\1")[\2]', adoc_content)
    
    return adoc_content

def migrate_project(source_dir, target_dir):
    """
    迁移整个项目：
    1. 创建目标目录
    2. 遍历源目录所有文件
    3. 转换.adoc文件为.typ
    4. 复制其他资源文件
    """
    Path(target_dir).mkdir(exist_ok=True)
    conversion_report = []
    
    for root, dirs, files in os.walk(source_dir):
        # 在目标目录创建对应子目录
        rel_path = os.path.relpath(root, source_dir)
        target_path = os.path.join(target_dir, rel_path)
        os.makedirs(target_path, exist_ok=True)
        
        for file in files:
            src_file = os.path.join(root, file)
            dest_file = os.path.join(target_path, file)
            
            # 处理.adoc文件
            if file.endswith('.adoc'):
                try:
                    with open(src_file, 'r', encoding='utf-8') as f:
                        adoc_content = f.read()
                    
                    typst_content = convert_adoc_to_typst(adoc_content)
                    new_name = os.path.splitext(file)[0] + '.typ'
                    dest_file = os.path.join(target_path, new_name)
                    
                    with open(dest_file, 'w', encoding='utf-8') as f:
                        f.write(typst_content)
                    
                    conversion_report.append(f"SUCCESS: {src_file} -> {dest_file}")
                except Exception as e:
                    conversion_report.append(f"ERROR: {src_file} - {str(e)}")
            
            # 复制非文本资源（图片等）
            elif not file.endswith(('.txt', '.html', '.yml')):
                try:
                    shutil.copy2(src_file, dest_file)
                    conversion_report.append(f"COPIED: {src_file} -> {dest_file}")
                except Exception as e:
                    conversion_report.append(f"COPY ERROR: {src_file} - {str(e)}")
    
    # 生成转换报告
    report_path = os.path.join(target_dir, "conversion_report.txt")
    with open(report_path, 'w', encoding='utf-8') as f:
        f.write("\n".join(conversion_report))
    
    return len(conversion_report)

if __name__ == "__main__":
    SOURCE_DIR = "clojure-book"
    TARGET_DIR = "typst-book"
    
    print(f"开始迁移项目: {SOURCE_DIR} -> {TARGET_DIR}")
    count = migrate_project(SOURCE_DIR, TARGET_DIR)
    print(f"迁移完成! 处理文件总数: {count}")
    print(f"转换报告已保存至: {os.path.join(TARGET_DIR, 'conversion_report.txt')}")